/*
 * =====================================================================================
 *
 *       Filename:  PthreadMutexLock.h
 *
 *    Description:  PthreadMutexLock.h
 *
 *         Author:  Younghyun Jo (2013-20887)
 *   Organization:  Department of Computer Science and Engineering
 *                  Seoul National University
 *
 * =====================================================================================
 */

#include <pthread.h>

#ifndef PARTICIPANT
  #define PARTICIPANT Participant
#endif

#include <tmc/spin.h>
#include <tmc/sync.h>
#include <arch/atomic.h>
#include <arch/inline.h>
#include <sys/time.h>

#define spin_lock_init(lock) tmc_spin_mutex_init(lock)
#define spin_lock_destruct(lock) {;} // nothing
#define spin_lock_acquire tmc_spin_mutex_lock
#define spin_lock_release tmc_spin_mutex_unlock
#define spin_lock_t tmc_spin_mutex_t

class Participant;

class PthreadMutexLock {
  public:
    PthreadMutexLock(const int numParticipants)
    {
      pthread_mutex_init(&mutex, NULL);
    }

    ~PthreadMutexLock()
    {
      pthread_mutex_destroy(&mutex);
    }

    inline void finalize_initialization() {}

    int sharedVar;
    pthread_mutex_t mutex;
};

class Participant {
  public:
    Participant(PthreadMutexLock* const mutexLock)
      : _mutexLock(mutexLock) {}

    inline bool synchronize() const {
      pthread_mutex_lock(&(_mutexLock->mutex));
      _mutexLock->sharedVar += 1;
      pthread_mutex_unlock(&(_mutexLock->mutex));
    }

  private:
    PthreadMutexLock* const _mutexLock;
};

